package com.chucang.shucang.usr.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.chucang.shucang.common.mq.constant.RabbitConstant;
import com.chucang.shucang.usr.entity.UserBillRecordEntity;
import com.chucang.shucang.usr.entity.UserWalletEntity;
import com.chucang.shucang.usr.service.UserBillRecordService;
import com.chucang.shucang.usr.service.UserWalletService;
import com.rabbitmq.client.Channel;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author flitsneak
 * @email flitsneak@gmail.com
 * @date 2022/10/23 22:31
 * @description 钱包充值
 */
@Slf4j
@Component
@RequiredArgsConstructor
@RabbitListener(queues = RabbitConstant.ALIPAY_RECHARGE_SUCCESS_QUEUE)
public class AliPayRechargeSuccessListener {

    private final UserBillRecordService userBillRecordService;
    private final UserWalletService userWalletService;

    @RabbitHandler
    public void aliPayRechargeSuccessListener(String billSn, Channel channel, Message message) throws IOException {
        try {
            LambdaQueryWrapper<UserBillRecordEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(UserBillRecordEntity::getBillSn, billSn)
                    .select();
            UserBillRecordEntity one = userBillRecordService.getOne(lambdaQueryWrapper);
            //更新账单状态
            LambdaUpdateWrapper<UserBillRecordEntity> lambdaUpdateWrapper = new LambdaUpdateWrapper<>();
            lambdaUpdateWrapper.eq(UserBillRecordEntity::getBillSn, billSn)
                    .set(UserBillRecordEntity::getStatus, 1);
            userBillRecordService.update(lambdaUpdateWrapper);
            //更新钱包余额
            LambdaQueryWrapper<UserWalletEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserWalletEntity::getUserId, one.getUserId())
                    .select();
            UserWalletEntity serviceOne = userWalletService.getOne(queryWrapper);
            LambdaUpdateWrapper<UserWalletEntity> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(UserWalletEntity::getId, serviceOne.getId())
                    .set(UserWalletEntity::getBalance, serviceOne.getBalance().add(one.getAmount()));
            userWalletService.update(updateWrapper);
        } catch (Exception e) {
            log.error("钱包充值异常！");
            channel.basicReject(message.getMessageProperties().getDeliveryTag(), true);
        }
    }

}
